﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ModelBinder.Extension.AspNetCore.FromSmartBody;
using VueShopApi.Common;
using VueShopApi.Entities;

namespace VueShopApi.Controllers
{
    [ApiExplorerSettings(GroupName = "v1")]
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly ILogger<LoginController> _logger;
        private readonly IFreeSql _context;

        public LoginController(ILogger<LoginController> logger, IFreeSql context)
        {
            _logger = logger;
            _context = context;
        }

        /// <summary>
        /// 管理员登录
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="jwt"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Post([FromSmartBody] string username, [FromSmartBody] string password, [FromServices] JwtHelper jwt)
        {
            _logger.LogDebug("login => username:{0},password:{1}", username, password);
            var manager = await _context.Select<SpManager>().Where(u => u.MgName == username.Trim()).ToOneAsync();
            if (manager == null)
                return ServerResponse.No("用户名或密码错误");

            if (manager.RoleId < 0)
                return ServerResponse.No("该用户没有权限登录");

            if (manager.RoleId != 0 && manager.MgState != 1)
                return ServerResponse.No("该用户已经被禁用");

            if (BCrypt.Net.BCrypt.Verify(password, manager.MgPwd))
            {
                var token = jwt.IssueToken(new ManagerPrincipal(manager.MgId, manager.RoleId));
                return ServerResponse.Yes(new
                {
                    id = manager.MgId,
                    rid = manager.RoleId,
                    username = manager.MgName,
                    mobile = manager.MgMobile,
                    email = manager.MgEmail,
                    token
                });
            }

            return ServerResponse.No("用户名或密码错误");
        }
    }
}
